package Server6BySelf;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private static Socket socket;
    private static Scanner sc=new Scanner(System.in);
    public void start(){
        try {
            System.out.println("正在链接服务端");
            socket=new Socket("localhost",8088);
            System.out.println("链接服务端成功");

            //收消息
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream is=socket.getInputStream();
                        InputStreamReader isr=new InputStreamReader(is,"utf-8");
                        BufferedReader br=new BufferedReader(isr);
                        String line;
                        while ((line= br.readLine())!=null){
                            System.out.println(line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            //发信息
            sendMessage();



        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void sendMessage() throws IOException {
        OutputStream fos=socket.getOutputStream();
        OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
        BufferedWriter bw=new BufferedWriter(osw);
        PrintWriter pw=new PrintWriter(bw,true);//设置为true才会自动换行发送
        while (true){
            System.out.println("输入信息，回车发送(0退出)");
            String line=sc.nextLine();
            if ("0".equals(line)){
                break;
            }
            pw.println(line);
        }
    }

    public static void main(String[] args) {
        Client client=new Client();
        client.start();
    }
}
